package com.itheima.threadtest4;

import java.util.Random;

public class MyThread extends Thread{

    //100分三个红包
    static double money = 100 ;
    static int count = 3 ;

    //最小金额
    public static final double MIN = 0.01 ;

    public void run() {

        //对共享数据的检查和修改要一起
        synchronized(MyThread.class) {
            //判断变量是否分完

            //首先看 count == 0 如果是则表明分完了
            if (count == 0 ) {
                System.out.println(this.getName() + "没有抢到红包");
            } else {
                //进行分红包的逻辑
                double prize = 0 ;  //分到的红包的金额
                Random r = new Random() ;   //随机函数类
                if (count == 1) {
                    // 如果是最后一个红包就不用随机数 直接分完
                    prize = money ;
                } else {
                    // 每个红包在发放的时候不能发完
                    // prize = 100 - 0.01 - 0.01
                    // prize = money - ( count - 1 ) * money count 是剩余的红包数量
                    double bounds = r.nextDouble(money) - (count - 1 ) * MIN ;  //最大金额
                    prize = r.nextDouble(bounds) ;

                    if (prize < MIN) {
                        prize = MIN ;
                    }
                }

                // 从 money 中减去 金额
                money = money - prize ;

                // 红包数 - 1
                count -- ;
                System.out.println(this.getName() + "抢到了" + prize + "元 ");
            }
        }
    }
}
